import fs from '../fs'
import pathExists from '../path-exists'
import path from '../../node/path'


const getMode = options => {
    const defaults = { mode: 0o777 }
    if (typeof options === 'number') return options
    return ({ ...defaults, ...options }).mode
}

export function makeDir (dir, options?) {
    return new Promise((res, rej) => {
        let parentPath = path.dirname(dir);
        if (!pathExists.pathExistsSync(parentPath)) {
            makeDirSync(parentPath, options);
            try {
                res(fs.mkdir(dir, getMode(options)))
            } catch (err) {
                rej(err)
            }
        } else {
            try {
                res(fs.mkdir(dir, getMode(options)))
            } catch (err) {
                rej(err)
            }
        }
    })
}

export var makeDirSync = (dir, options?) => {
    let parentPath = path.dirname(dir);
    if (!pathExists.pathExistsSync(parentPath)) {
        makeDirSync(parentPath, options)
    }

    return fs.mkdirSync(dir, getMode(options))
}
